<template>
  <div class="publish-page">
    <el-card class="form-card">
      <template #header>
        <h3>发布校园活动</h3>
      </template>

      <!-- 权限提示 -->
      <el-alert
        v-if="!isAdmin"
        title="权限不足"
        type="warning"
        :closable="false"
        show-icon
        style="margin-bottom: 20px"
      >
        只有管理员才能发布活动，普通用户无此权限
      </el-alert>

      <!-- 表单 -->
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        :disabled="!isAdmin"
      >
        <!-- 活动标题 -->
        <el-form-item label="活动标题" prop="title">
          <el-input
            v-model="formData.title"
            placeholder="请输入活动标题"
            maxlength="100"
            show-word-limit
            clearable
          />
        </el-form-item>

        <!-- 活动简介 -->
        <el-form-item label="活动简介" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入活动简介"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 开始时间 -->
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <!-- 结束时间 -->
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="formData.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <!-- 活动地点 -->
        <el-form-item label="活动地点" prop="location">
          <el-input
            v-model="formData.location"
            placeholder="请输入活动地点"
            maxlength="100"
            clearable
          />
        </el-form-item>

        <!-- 人数上限 -->
        <el-form-item label="人数上限" prop="maxParticipants">
          <el-input-number
            v-model="formData.maxParticipants"
            :min="0"
            :max="10000"
            style="width: 200px"
          />
          <span class="tip">0表示不限制人数</span>
        </el-form-item>

        <!-- 活动图片 -->
        <el-form-item label="活动图片">
          <el-upload
            v-model:file-list="fileList"
            action="/api/activity/upload/image"
            :headers="uploadHeaders"
            list-type="picture-card"
            :on-success="onUploadSuccess"
            :on-remove="onRemoveImage"
            :before-upload="beforeUpload"
            :limit="6"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="tip">最多上传6张图片，每张不超过5MB</div>
        </el-form-item>

        <!-- 按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            :disabled="!isAdmin"
            @click="onSubmit"
          >
            发布活动
          </el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { reqPublishActivity } from '@/api/activity/index'
import useUserStore from '@/stores/modules/user'

const userStore = useUserStore()

// 判断是否为管理员
const isAdmin = computed(() => {
  return (
    userStore.buttons?.includes('activity:publish')
  )
})

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  title: '',
  description: '',
  startTime: '',
  endTime: '',
  location: '',
  maxParticipants: 0
})

// 图片列表
const fileList = ref<UploadUserFile[]>([])
const imageUrls = ref<string[]>([])

// 加载状态
const loading = ref(false)

// 上传请求头
const uploadHeaders = computed(() => ({
  token: userStore.token || ''
}))

// 表单验证规则
const formRules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入活动标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度为2-100个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入活动简介', trigger: 'blur' },
    { min: 10, max: 500, message: '简介长度为10-500个字符', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ]
})

// 上传前验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  return true
}

// 上传成功回调
const onUploadSuccess = (response: any) => {
  if (response.code === 200) {
    imageUrls.value.push(response.data.url)
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

// 移除图片
const onRemoveImage = (file: UploadUserFile) => {
  const index = fileList.value.findIndex(item => item.uid === file.uid)
  if (index > -1) {
    imageUrls.value.splice(index, 1)
  }
}

// 提交表单
const onSubmit = () => {
  if (!isAdmin.value) {
    ElMessage.warning('您没有权限发布活动')
    return
  }

  if (!formRef.value) return

  formRef.value.validate((valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息')
      return
    }

    // 验证时间逻辑
    if (formData.startTime >= formData.endTime) {
      ElMessage.error('结束时间必须晚于开始时间')
      return
    }

    // 提交数据
    submitForm()
  })
}

// 提交数据到后端
const submitForm = async () => {
  loading.value = true

  try {
    const data = {
      title: formData.title,
      description: formData.description,
      startTime: formData.startTime,
      endTime: formData.endTime,
      location: formData.location,
      maxParticipants: formData.maxParticipants,
      images: imageUrls.value
    }

    const result: any = await reqPublishActivity(data)

    if (result.code === 200) {
      ElMessage.success('活动发布成功！')
      onReset()
    } else {
      ElMessage.error(result.message || '发布失败')
    }
  } catch (error: any) {
    console.error('发布活动失败:', error)
    ElMessage.error(error.message || '发布失败，请重试')
  } finally {
    loading.value = false
  }
}

// 重置表单
const onReset = () => {
  formRef.value?.resetFields()
  fileList.value = []
  imageUrls.value = []
  formData.maxParticipants = 0
}
</script>

<style scoped lang="scss">
.publish-page {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.form-card {
  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
  }
}

.tip {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}
</style>
